<template>
  <Page auto-content-height>
    <Grid ref="gridRef">
      <template #actionList="{ row }">
        <template
          v-for="(item, index) in row.actionList"
          :key="index"
          :value="item.authorityId"
        >
          <Checkbox
            :disabled="item.disabled"
            :checked="isChecked(item.authorityId)"
            :id="item.authorityId"
            @change="checkboxChange"
            ><span :title="item.actionDesc">{{
              item.actionName
            }}</span></Checkbox
          >
        </template>
        <template v-if="row.parentId != 0">
          <Button
            type="dashed"
            size="small"
            @click="roleModel?.open({ menuId: row.menuId })"
            >添加</Button
          >
        </template>
      </template>
    </Grid>
  </Page>
  <RoleModel ref="roleModel" @success="refreshData" />
</template>

<script lang="ts" setup>
defineOptions({
  name: 'RoleAuth',
});
import { computed, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, Checkbox, message } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  authGridOptions,
  handleRoleId,
  AuthorityMenuList,
} from '../data/options';
import { AuthorityRole, roleGrant } from '../data/api';
import RoleModel from './roleModel.vue';

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: authGridOptions,
});

const gridRef = ref();
const roleModel = ref<any>(null);
const selectedIds = ref<string[]>([]);
const emit = defineEmits(['success']);

// 按钮是否选中
const isChecked = computed(() => {
  return (authorityId: string) => {
    if (!authorityId) return false;
    return selectedIds.value.includes(authorityId);
  };
});

// 刷新数据
const refreshData = async () => {
  await gridApi.query();
  GetAuthorityRole();
  setTimeout(() => {
    gridApi.grid?.setAllTreeExpand(true);
  }, 100);
};

// 初始化数据渲染
const GetAuthorityRole = async () => {
  let res: any = await AuthorityRole({ roleId: handleRoleId.value });
  setTimeout(() => {
    selectedIds.value.length = 0;
    res.data.forEach((item: any) => {
      AuthorityMenuList.value.forEach((row: any) => {
        if (item.authorityId == row.authorityId) {
          row.isChecked = true;
        }
        row.actionList.forEach((action: any) => {
          if (item.authorityId == action.authorityId) {
            console.log('action.authorityId', action.authorityId);
            selectedIds.value.push(action.authorityId);
          }
        });
      });
    });
  }, 100);
  console.log('selectedIds', selectedIds.value);
};

// 选中状态改变
const checkboxChange = (e: any) => {
  if (selectedIds.value.includes(e.target.id)) {
    selectedIds.value.splice(selectedIds.value.indexOf(e.target.id), 1);
  } else {
    selectedIds.value.push(e.target.id);
  }
};

// 获取选择的id
const getIds = () => {
  const records = gridApi.grid.getCheckboxRecords();
  const ids = records.map((item: any) => item.authorityId);
  const arr = [...selectedIds.value, ...ids];
  const set = new Set(arr);
  const array = Array.from(set);
  const authorityIds = array.filter((element) => {
    return element !== undefined;
  });
  return authorityIds.join() || '';
};

const onConfirm = async () => {
  console.log('onConfirm');
  let params = {
    roleId: handleRoleId.value,
    authorityIds: getIds(),
  };
  let res: any = await roleGrant(params);
  message.success(res.message);
  emit('success');
};

defineExpose({
  refreshData,
  onConfirm,
});
</script>

<style lang="scss" scoped></style>
